//
// Created by linciping on 2020/9/16.
//
#include "util.h"

char *jstringToString(JNIEnv *env, jstring jstr) {
    char *rtn = NULL;
    jclass clsString = (*env)->FindClass(env, "java/lang/String");
    jstring strEncode = (*env)->NewStringUTF(env, "UTF-8");
    jmethodID methodGetBytes = (*env)->GetMethodID(env, clsString, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray strBytes = (jbyteArray) (*env)->CallObjectMethod(env, jstr, methodGetBytes, strEncode);
    jsize strLength = (*env)->GetArrayLength(env, strBytes);
    jbyte *ba = (*env)->GetByteArrayElements(env, strBytes, JNI_FALSE);
    if (strLength > 0) {
        rtn = (char *) malloc(strLength + 1);
        memcpy(rtn, ba, strLength);
        rtn[strLength] = 0;
    }
    (*env)->ReleaseByteArrayElements(env, strBytes, ba, 0);
    return rtn;
}

